<template>
  <div id="questionnaires-create" class="clear">
    <div class="under-header-fixed-container">
      <div class="page-title-holder main-container container-limited flex content-space-between">
        <h2 class="page-title">新建问卷</h2>
        <div>
          <el-button type="primary" size="small"
                     @click="onSubmit" :loading="isLoading">保存</el-button>
          <el-button size="small" class="m-r-10" @click="cancel">取消</el-button>
        </div>
      </div>
    </div>
    <div class="main-container container-fluid container-limited page-holder clear">
      <div class="questionnaire-paper paper-card">
        <div class="questionnaire-content">
          <el-input class="title" v-model="title" placeholder="编辑问卷标题"/>
          <el-input v-model="desc" type="textarea" :rows="1" autosize
                    class="desc m-t-24" placeholder="添加问卷说明"/>
          <Questions class="m-t-24" :questions.sync="questions" :editable="true"/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Questions from './Questions';
import * as format from './format';

export default {
  name: 'QuestionnaireCreate', // 新建问卷
  components: { Questions },
  data() {
    return {
      title: '', // 问卷标题
      desc: '', // 问卷说明
      questions: JSON.parse(JSON.stringify(format.defaultQuestions)),
      isLoading: false, // 正在保存
    };
  },
  computed: {
    // 生成要保存的问卷数据
    initSaveParams() {
      return {
        title: this.title.trim() || '未设置问卷标题',
        desc: this.desc.trim(),
        questions: format.formatQuestions(this.questions),
      };
    },
  },
  methods: {
    // 保存问卷
    onSubmit() {
      this.isLoading = true;
      this.$api.questionnaires.create(this.initSaveParams)
        .then((res) => {
          this.$message.success('创建成功');
          this.$router.push(`/${this.$rp.QUESTIONNAIRES}/${res.data.id}`);
        })
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
    // 取消并返回列表
    cancel() {
      this.$confirm('当前问卷未保存，是否取消编辑？', '提示', {
        customClass: 'confirm-left',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => this.$router.push(`/${this.$rp.QUESTIONNAIRES}`))
        .catch(() => {});
    },
  },
};
</script>

<style></style>
